﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.Net;
using com.lover.common;
using System.IO;
using com.lover.astd.common.model;
using com.lover.common.http;

namespace com.lover.astd.common.partner.impl
{
    public class _6998Login : LoginImplBase
    {
        public _6998Login() : base() { }
        public override LoginResult login(ref List<Cookie> cookies, string verify_code = null, string extra = null)
        {
            LoginResult result = new LoginResult();
            logging();
            string token_url = "https://passport.6998.com/login";
            HttpResult resp = TransferMgr.doGetPure(token_url, ref cookies);
            if (resp == null) { result.StatusCode = LoginStatusCode.FailInGetToken; return result; }
            string content = resp.getContent();
            Regex re = new Regex(".*?[\"']+?(LT-\\w+?-\\w+?)[\"']+?.*?");
            Match m = re.Match(content);
            if (m == null || m.Groups == null || m.Groups.Count < 2) { result.StatusCode = LoginStatusCode.FailInGetToken; return result; }
            string lt_token = m.Groups[1].Value;

            logging();
            string loginurl = "https://passport.6998.com/login";
            string data = String.Format("hidUrl=&hidLoginTimes=&Username={0}&Password={1}&OTP=&LT={2}&LoginView=Login&UserLoginFrom=0&IsAccount=1", 
                _username, _password, lt_token);
            resp = TransferMgr.doPostPure(loginurl, data, ref cookies);
            if (resp == null) { result.StatusCode = LoginStatusCode.FailInLogin; return result; }

            string retstr = resp.getContent();

            if (!retstr.Contains("JSONP.src"))
            {
                result.StatusCode = LoginStatusCode.FailInLogin;
                return result;
            }

            findingServerUrl();
            // 查找serverid字符串
            token_url = "https://passport.6998.com/api/GetClientToken?jsoncallback=updatestart&rand=" + _rand.NextDouble();
            resp = TransferMgr.doGetPure(token_url, ref cookies);
            if (resp == null) { result.StatusCode = LoginStatusCode.FailInGetToken; return result; }
            //updatestart(".....")
            content = resp.getContent();
            content = content.Replace("updatestart(\"", "");
            content = content.Replace("\")", "");

            string client_token = content;
            string redirecturl = String.Format("https://passport.6998.com/jump?clienttoken={0}&service=http://account.6998.com/mygame_login_astd-3-0.html", client_token);

            resp = TransferMgr.doGetPure(redirecturl, ref cookies);
            if (resp == null) { result.StatusCode = LoginStatusCode.FailInFindingGameUrl; return result; }
            string former_url = redirecturl;
            redirecturl = resp.getExtraHeader("Location");
            //https://passport.6998.com/login?service=http%3a%2f%2faccount.6998.com%2fmygame_login_astd-3-0.html
            makeSureValidUri(former_url, ref redirecturl);
            if (redirecturl == null || redirecturl == "") { result.StatusCode = LoginStatusCode.FailInFindingGameUrl; return result; }

            resp = TransferMgr.doGetPure(redirecturl, ref cookies);
            if (resp == null) { result.StatusCode = LoginStatusCode.FailInFindingGameUrl; return result; }

            goingToGameUrl();

myloop:
            content = resp.getContent();
            
            re = new Regex(".*?JSONP\\.src.*?=.*?[\"']+?([^\"']*?)[\"']+?.*");
            m = re.Match(content);
            if (m == null || m.Groups == null || m.Groups.Count < 2) { result.StatusCode = LoginStatusCode.FailInGetSession; return result; }
            string uc55_url = m.Groups[1].Value;
            re = new Regex(".*?rCallbackURL.*?=.*?[\"']+?([^\"']*?)[\"']+?.*");
            m = re.Match(content);
            if (m == null || m.Groups == null || m.Groups.Count < 2) { result.StatusCode = LoginStatusCode.FailInGetSession; return result; }
            string game_container_url = m.Groups[1].Value;
            //http://account.6998.com/mygame_login_astd-3-0.html?ticket=ST-198142-BYkJecrA2JT4iOEdXqF4Q0HaVReI2edaDWe
            // 或者
            //http://account.6998.com/account/loginjump?url=%2fmygame_login_astd-3-0.html%3fticket%3dST-123042-Hga9ldAEyy6gtqafNp5AVY0Rbi70j6lAwcy&ticket=ST-197248-fFoDfiMVNyjDoHWzAfVb7ddDB0hElVyDdoE
            // 这里访问game_container_url的时候, 如果还要跳转, 那么就是因为没有.ASPXAUTH的cookie, 需要继续下一条验证登陆
            makeSureValidUri(redirecturl, ref uc55_url);
            makeSureValidUri(redirecturl, ref game_container_url);
            resp = TransferMgr.doGetPure(uc55_url + "&rand=" + _rand.NextDouble(), ref cookies);
            if (resp == null) { result.StatusCode = LoginStatusCode.FailInGetSession; return result; }

            resp = TransferMgr.doGetPure(game_container_url, ref cookies);
            if (resp == null) { result.StatusCode = LoginStatusCode.FailInGetSession; return result; }

            gettingSession();

            if (resp.StatusCode == 302)
            {
                string login_url = resp.getExtraHeader("Location");
                // /Account/Login?ReturnUrl=%2fmygame_login_astd-3-0.html%3fticket%3dST-123042-Hga9ldAEyy6gtqafNp5AVY0Rbi70j6lAwcy&ticket=ST-123042-Hga9ldAEyy6gtqafNp5AVY0Rbi70j6lAwcy
                // 或者
                // http://account.6998.com/mygame_login_astd-3-0.html?ticket=ST-198142-BYkJecrA2JT4iOEdXqF4Q0HaVReI2edaDWe
                makeSureValidUri(game_container_url, ref login_url);
                resp = TransferMgr.doGetPure(login_url, ref cookies);
                if (resp == null) { result.StatusCode = LoginStatusCode.FailInGetSession; return result; }
                //302
                if (resp.StatusCode == 302)
                {
                    string index_svc_url = resp.getExtraHeader("Location");
                    resp = TransferMgr.doGetPure(index_svc_url, ref cookies);
                    if (resp == null) { result.StatusCode = LoginStatusCode.FailInGetSession; return result; }

                    goto myloop;
                }
                else
                {
                    content = resp.getContent();
                    re = new Regex("<frame.*?src=[\"']+?(.*?start\\.action.*?)[\"']+?.*");
                    m = re.Match(content);
                    if (m == null || m.Groups == null || m.Groups.Count < 2) { result.StatusCode = LoginStatusCode.FailInGetSession; return result; }

                    string gameurl = m.Groups[1].Value;
                    gameurl = gameurl.Replace("&amp;", "&");
                    processStartGame(gameurl, result, ref cookies, login_url);
                }
            }
            else
            {
                content = resp.getContent();
                re = new Regex("<frame.*?src=[\"']+?(.*?start\\.action.*?)[\"']+?.*");
                m = re.Match(content);
                if (m == null || m.Groups == null || m.Groups.Count < 2) { result.StatusCode = LoginStatusCode.FailInGetSession; return result; }

                string gameurl = m.Groups[1].Value;
                processStartGame(gameurl, result, ref cookies, game_container_url);
            }
            
            return result;
        }
    }
}
